package de.unikoblenz.west.csxpoi.server;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.http.HTTPRepository;

/**
 * Revises POI data by detecting and merging duplicates.
 */
public class RevisionEngine extends HttpServlet {

	private static final long serialVersionUID = 1L;

	/**
	 * Handles GET requests.
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// TODO: as standalone instead of servlet?

		PrintWriter writer = ServletHelper.utf8Writer(response);
		RdfWriter.setN3ContentType(response);
		ServletHelper.disableCaching(response);

		Repository repository = new HTTPRepository(Constants.SESAME_SERVER,
				Constants.REPOSITORY_ID);

		try {
			repository.initialize();
			RepositoryConnection connection = repository.getConnection();

			try {

				DuplicatePoiFinder.execute(connection, writer);

			} catch (MalformedQueryException e) {
				e.printStackTrace();
			} catch (QueryEvaluationException e) {
				e.printStackTrace();
			} catch (SimilarityException e) {
				e.printStackTrace();
			} finally {
				connection.close();
			}
		} catch (RepositoryException e) {
			e.printStackTrace();
		}
	}

}
